<?php
define('WORKER_ROOT_PATH',dirname(dirname(dirname(__FILE__))));
define('WORKER_UPLOAD_PATH',WORKER_ROOT_PATH.'/temp/worker');
define('LOG_PATH',WORKER_ROOT_PATH.'/logs/worker');

require_once(WORKER_ROOT_PATH . '/www/appconf.php');

$gm_servers = $site_global_config['GEARMAN_SERVERS'];
$func_a = array('upload_photo', 'timeline_feed');
$datetime = date("Y-m-d H:i:s", time());
echo "\n$datetime \n";

$worker = new GearmanWorker();
$worker->addServers($gm_servers);
foreach ($func_a as $func) {
    $worker->addFunction($func, "{$func}_function");
    echo "Initializing worker, addFunction->{$func}\n";
}

# Set the timeout to 20 minutes
$worker->setTimeout(20*60*1000);

# start te worker listening for job submissions
echo "\nWorker is started, waiting for job...\n\n";

//start while
while (@$worker->work() || $worker->returnCode() == GEARMAN_TIMEOUT) {

    if ($worker->returnCode() == GEARMAN_TIMEOUT) {
        # Normally one would want to do something useful here ...
        #echo "\n";
        #echo date("Y-m-d H:i:s", time()) . " | action:\"worker_timeout\", comment:\"Waiting for next job...\"\n\n";
        continue;
    }

    if ($worker->returnCode() != GEARMAN_SUCCESS) {
        echo "return_code: " . $worker->returnCode() . "\n";
        break;
    }

}
//end while;


### start function

/* upload photo to remote server and resize */
function upload_photo_function($job){
	$arg = json_decode($job->workload(),true);

	$file = $arg['file'];
	$dir = $arg['dir'];
	$url = $arg['url'];
	$domain = $arg['domain'];
	$maxwidth = $arg['maxwidth'];
	$maxheight = $arg['maxheight'];

	//get file to temp dir
	$photo = file_get_contents($file);
	$filename = basename($file);
	if(!$photo){
		toLog('upload_photo.log','file:'.$file.' get photo fail');
		return json_encode(array('status'=>'fail'));
	}
	file_put_contents(WORKER_UPLOAD_PATH.'/'.$filename,$photo);
	chmod(WORKER_UPLOAD_PATH.'/'.$filename,0777);
	$tmpfile = WORKER_UPLOAD_PATH.'/'.$filename;

	//resize photo
	if(!file_exists($tmpfile)){
		toLog('upload_photo.log','file:'.$tmpfile.' not exist');
		return json_encode(array('status'=>'fail'));
	}

	$imginfo = getimagesize($tmpfile);	
	if(!$imginfo){
		toLog('upload_photo.log','file:'.$tmpfile.' not photo');
		return json_encode(array('status'=>'fail'));
	}

	$imghandle = "";
	if($imginfo[0]>$maxwidth || $imginfo[1]>$maxheight){
		$imghandle = $imghandle ." -resize ".(int)$maxwidth."x".(int)$maxheight." ";
	}
	if($imginfo['channels']!=3){
		$imghandle = $imghandle ."  -colorspace rgb ";
	}

	if($imghandle!=''){
		exec("convert  ".$imghandle." '".$tmpfile."' '".$tmpfile."'");
	}

	$size = filesize($tmpfile);

	//post fields
	$fields = array();
	$fields['pic'] = '@'.$tmpfile;
	$fields['path'] = $dir;
	$fields['filename'] = $filename;

	$ch = curl_init();
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_URL, $url);
	curl_setopt($ch, CURLOPT_POST, true);
	curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
	$response = curl_exec($ch);

	//delete temp file
	unlink($tmpfile);
	
	if ($error = curl_error($ch) ) {
		toLog('upload_photo.log','file:'.$tmpfile.' upload to remote fail');
		return json_encode(array('status'=>'fail'));
	}
	curl_close($ch);

	//return 
	$response = json_decode($response,true);
	$response['domain'] = $domain;
	$response['size'] = $size;
	toLog('upload_photo.log','file:'.$file.' upload complete');
	return json_encode($response);
}


/* feed timeline */
function timeline_feed_function($job) {
	$arg = json_decode($job->workload(),true);
	$timeline_obj = getLibClass('TimeLineWorker');
	$timeline_obj->feed($arg);
}


/* write log */
function toLog($log,$content){
	$content = "[".date("Y-m-d H:i:s")."] ".$content."\r\n";
	file_put_contents(LOG_PATH.'/'.$log,$content,FILE_APPEND);
	chmod(LOG_PATH.'/'.$log,0777);
}

?>
